<template>
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
        <el-form ref="formRef" :model="formData" label-width="80px" :rules="formRules">
            
            
            <el-form-item label="菜单类型" prop="menuType" required>
                
                
                <div v-if="mode === 'add'">
                    <el-radio-group v-model="formData.menuType"
                                    v-if="formData.menuType === MenuEnum.CATALOGUE && formData.pid===0 ">
                        <el-radio :label="MenuEnum.CATALOGUE">目录</el-radio>
                    </el-radio-group>
                    
                    <el-radio-group v-model="formData.menuType" v-else-if="formData.menuType === MenuEnum.CATALOGUE">
                        <el-radio :label="MenuEnum.CATALOGUE">目录</el-radio>
                        <el-radio :label="MenuEnum.MENU">菜单</el-radio>
                    </el-radio-group>
                    
                    
                    <el-radio-group v-model="formData.menuType" v-else-if="formData.menuType === MenuEnum.MENU">
                        <el-radio :label="MenuEnum.BUTTON">按钮</el-radio>
                    </el-radio-group>
                </div>
                
                
                <div v-else-if="mode === 'edit'">
                    <el-radio-group v-model="formData.menuType">
                        <el-radio :label="MenuEnum.CATALOGUE " v-if="formData.menuType === MenuEnum.CATALOGUE">目录
                        </el-radio>
                        <el-radio :label="MenuEnum.MENU" v-if="formData.menuType === MenuEnum.MENU">菜单</el-radio>
                        <el-radio :label="MenuEnum.BUTTON" v-if="formData.menuType === MenuEnum.BUTTON">按钮</el-radio>
                    </el-radio-group>
                </div>
            
            
            </el-form-item>
            
            
            <el-form-item label="菜单名称" prop="menuName">
                <el-input v-model="formData.menuName" placeholder="请输入菜单名称" clearable/>
            </el-form-item>
            
            <el-form-item
                v-if="formData.menuType !== MenuEnum.BUTTON"
                label="菜单图标"
                prop="menuIcon"
            >
                <icon-picker class="flex-1" v-model="formData.menuIcon"/>
            </el-form-item>
            
            <el-form-item
                v-if="formData.menuType !== MenuEnum.BUTTON"
                label="路由路径"
                prop="paths"
            >
                <div class="flex-1">
                    <el-input v-model="formData.paths" placeholder="请输入路由路径" clearable/>
                    <div class="form-tips">
                        访问的路由地址，如：`admin`，如外网地址需内链访问则以`http(s)://`开头
                    </div>
                </div>
            
            </el-form-item>
            
            
            <el-form-item
                v-if="formData.menuType === MenuEnum.MENU"
                label="组件路径"
                prop="component"
            >
                <div class="flex-1">
                    <el-autocomplete
                        class="w-full"
                        v-model="formData.component"
                        :fetch-suggestions="querySearch"
                        clearable
                        placeholder="请输入组件路径"
                    />
                    
                    <div class="form-tips">
                        访问的组件路径，如：`permission/admin/index`，默认在`views`目录下
                    </div>
                </div>
            
            </el-form-item>
            
            
            <el-form-item
                v-if="formData.menuType !== MenuEnum.CATALOGUE"
                label="权限字符"
                prop="perms">
                
                <div class="flex-1">
                    
                    <el-select v-model="formData.perms"
                               class="w-full"
                               clearable
                               placeholder="请输入权限字符">
                        <el-option
                            v-for="item in options"
                            :key="item.key"
                            :label="item.value"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                    <div class="form-tips">
                        将作为server端API验权使用，如`system:admin:list`，请谨慎修改
                    </div>
                </div>
            </el-form-item>
            
            
            <el-form-item
                v-if="formData.menuType === MenuEnum.MENU"
                label="是否缓存"
                prop="isCache"
                required
            >
                <div>
                    <el-radio-group v-model="formData.isCache">
                        <el-radio :label="1">缓存</el-radio>
                        <el-radio :label="0">不缓存</el-radio>
                    </el-radio-group>
                    <div class="form-tips">选择缓存则会被`keep-alive`缓存</div>
                </div>
            </el-form-item>
            
            
            <el-form-item
                v-if="formData.menuType !== MenuEnum.BUTTON"
                label="是否显示"
                prop="isShow"
                required
            >
                <div>
                    <el-radio-group v-model="formData.isShow">
                        <el-radio :label="1">显示</el-radio>
                        <el-radio :label="0">隐藏</el-radio>
                    </el-radio-group>
                    <div class="form-tips">
                        选择隐藏则路由将不会出现在侧边栏，但仍然可以访问
                    </div>
                </div>
            </el-form-item>
            
            
            <el-form-item
                v-if="formData.menuType !== MenuEnum.BUTTON"
                label="菜单状态"
                prop="isDisable"
                required
            >
                <div>
                    <el-radio-group v-model="formData.isDisable">
                        <el-radio :label="0">正常</el-radio>
                        <el-radio :label="1">停用</el-radio>
                    </el-radio-group>
                    <div class="form-tips">选择停用则路由将不会出现在侧边栏，也不能被访问</div>
                </div>
            </el-form-item>
            
            <el-form-item label="菜单排序" prop="menuSort">
                <div>
                    <el-input-number v-model="formData.menuSort" :max="9999"/>
                    <div class="form-tips">数值越大越排前</div>
                </div>
            </el-form-item>
        
        </el-form>
    </popup>
</template>
<script lang="ts" setup>
import Popup from '@/components/popup/index.vue'

import {MenuEnum} from "@/config/enums/appEnums";
import {getRefAllViewModulesNameArray} from "@/manager/base/ViewsManager";
import {Ref} from "vue";
import {FormInstance} from "element-plus";
import feedback from "@/utils/feedback";
import {
    getSystemAuthMenuDetail,
    getSystemAuthMenuPrem, optSystemAuthMenuAdd,
    optSystemAuthMenuEdit
} from "@/api/system/SystemAuthMenuController";

const popupRef = shallowRef<InstanceType<typeof Popup>>()
const formRef = shallowRef<FormInstance>()


const formData = reactive({
    
    id: '',
    //父级id
    pid: 0,
    //类型
    menuType: null,
    //图标
    menuIcon: '',
    //名称
    menuName: '',
    //排序号
    menuSort: 0,
    
    //权限链接
    perms: '',
    //前端组件
    component: '',
    
    //路由路径
    paths: '',
    //是否缓存 0=否， 1=是
    isCache: 0,
    //是否显示 0=否， 1=是
    isShow: 1,
    //是否禁用 0=否， 1=是
    isDisable: 0
})


/**
 * 定义标题
 */
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'add' ? '新增菜单' : '编辑菜单'
})


/**
 * 提交
 */
const emit = defineEmits(["success", "close"])

async function handleSubmit() {
    await formRef.value?.validate()
    mode.value == 'edit' ? await optSystemAuthMenuEdit(formData) : await optSystemAuthMenuAdd(formData)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
    
    
}

function handleClose() {
    formRef.value?.resetFields()
    emit('close')
    
}

/**
 * 获取当前枚举详情
 *
 * @param row
 */
async function getMenuDetail(row: Record<string, any>) {
    const data = await getSystemAuthMenuDetail({id: row.id})
    setFormData(data)
}

/**
 * 回写表单
 *
 * @param formData
 * @param data
 */
const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}


/**
 * 打开弹窗
 *
 * @param type
 */
function open(type = 'add') {
    mode.value = type
    popupRef.value?.open()
}

const options = ref([])

/**
 * 自动搜索组件
 *
 * @param queryString
 * @param cb
 */
function querySearch(queryString: string, cb: any) {
    const refAllViewModulesNameArray: Ref<string[]> = getRefAllViewModulesNameArray()
    
    const results = queryString ?
        refAllViewModulesNameArray.value.filter((item) => item.toLowerCase().includes(queryString.toLowerCase()))
        : refAllViewModulesNameArray.value
    
    cb(results.map((item) => ({value: item})))
}


onMounted(() => {
    getSystemAuthMenuPrem().then(response => {
        options.value = response
    })
})


defineExpose({
    open,
    setFormData,
    getMenuDetail
})


/**
 * 路由规则
 */
const formRules = {
    pid: [
        {
            required: true,
            message: '请选择父级菜单',
            trigger: ['blur', 'change']
        }
    ],
    menuName: [
        {
            required: true,
            message: '请输入菜单名称',
            trigger: 'blur'
        }
    ],
    paths: [
        {
            required: true,
            message: '请输入路由地址',
            trigger: 'blur'
        }
    ],
    component: [
        {
            required: true,
            message: '请输入组件地址',
            trigger: 'blur'
        }
    ]
}
</script>
